package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.AdminAmongRoleMapper;
import com.qingcheng.dao.AdminMapper;
import com.qingcheng.dao.RoleMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.pojo.system.AdminAmongRole;
import com.qingcheng.pojo.system.Role;
import com.qingcheng.service.system.AdminService;
import com.qingcheng.util.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminAmongRoleMapper adminAmongRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 返回全部记录
     * @return
     */
    public List<Admin> findAll() {
        return adminMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Admin> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectAll();
        return new PageResult<Admin>(admins.getTotal(),admins.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Admin> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return adminMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Admin> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectByExample(example);
        return new PageResult<Admin>(admins.getTotal(),admins.getResult());
    }

    /**
     * 根据Id查询(已修改)
     * @param id
     * @return
     */
    public Map<String,Object> findById(Integer id) {
        //查询admin和roleIds
        Admin admin = adminMapper.selectByPrimaryKey(id);
        List<Integer> roleIds = adminAmongRoleMapper.findRoleIdsByAdminId(id);

        //写入map中
        Map<String,Object> map = new HashMap<>();
        map.put("id",admin.getId());
        map.put("username",admin.getLoginName());
        map.put("roleIds",roleIds);
        map.put("oldPass","");
        map.put("pass",null);
        map.put("checkPass",null);

        return map;
    }

    /**
     * 新增（已修改）
     * @param admin
     */
    public void add(Admin admin,List<Integer> roleIds) {

        //修改admin表
        String password = admin.getPassword();
        String gensalt = BCrypt.gensalt();//创建随机盐
        String encryptPassword = BCrypt.hashpw(password,gensalt);//生产密码
        admin.setPassword(encryptPassword);//设置加密的密码
        adminMapper.insert(admin); //admin.getId()可以获取增加后的主键id,只要在admin类的主键加上注解@GeneratedValue(strategy = GenerationType.IDENTITY)

        //修改amdin和role的中间表
        for(Integer roleId: roleIds){
            AdminAmongRole adminAmongRole = new AdminAmongRole();
            adminAmongRole.setAdminId(admin.getId());
            adminAmongRole.setRoleId(roleId);
            adminAmongRoleMapper.insert(adminAmongRole);
        }

    }

    /**
     * 修改(已修改)
     * @param map
     */
    public void update2(Map<String,Object> map) {

        //查询Admin
        Admin admin = adminMapper.selectByPrimaryKey(map.get("id"));
        System.out.println("admin_id:"+admin.getId());
        admin.setLoginName((String) map.get("username"));
        List<Integer> roleIds = (List<Integer>) map.get("roleIds");

        if(!(map.get("pass")==null)){ //判断前端传过来新密码
            String password = (String) map.get("pass");
            String gensalt = BCrypt.gensalt();//创建随机盐
            String encryptPassword = BCrypt.hashpw(password,gensalt);//生产密码
            admin.setPassword(encryptPassword);
        }
        adminMapper.updateByPrimaryKeySelective(admin);

        //清理admin和role的中间表，再重新设置
        Example example = new Example(AdminAmongRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("adminId",admin.getId());
        adminAmongRoleMapper.deleteByExample(example);

        for(Integer roleId:roleIds){
            AdminAmongRole adminAmongRole = new AdminAmongRole();
            adminAmongRole.setAdminId(admin.getId());
            adminAmongRole.setRoleId(roleId);
            adminAmongRoleMapper.insert(adminAmongRole);
        }
    }

    public Admin findAdminById(Integer id){
        return adminMapper.selectByPrimaryKey(id);
    }

    /**
     * 修改
     * @param admin
     */
    public void update(Admin admin) {

        adminMapper.updateByPrimaryKeySelective(admin);

    }

    /**
     *  删除
     * @param id
     */
    public void delete(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }


    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 用户名
            if(searchMap.get("loginName")!=null && !"".equals(searchMap.get("loginName"))){
//                criteria.andLike("loginName","%"+searchMap.get("loginName")+"%");
                criteria.andEqualTo("loginName",searchMap.get("loginName"));
            }
            // 密码
            if(searchMap.get("password")!=null && !"".equals(searchMap.get("password"))){
                criteria.andLike("password","%"+searchMap.get("password")+"%");
            }
            // 状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
            }

            // id
            if(searchMap.get("id")!=null ){
                criteria.andEqualTo("id",searchMap.get("id"));
            }

        }
        return example;
    }



}
